import numpy as np
import cv2
from matplotlib import pyplot as plt

#img1 = cv2.imread('../misc_pic/manowar_logo.jpg')  #0=cv2.IMREAD_GRAYSCALE
#img2 = cv2.imread('../misc_pic/manowar_cd.jpg')

img1=cv2.imread('../chess_pic/left01.jpg',cv2.IMREAD_GRAYSCALE)
img2=cv2.imread('../chess_pic/left02.jpg',cv2.IMREAD_GRAYSCALE)

#创建SIFT，detect/compute
sift=cv2.xfeatures2d.SIFT_create()
kp1,des1=sift.detectAndCompute(img1,None)
kp2,des2=sift.detectAndCompute(img2,None)

#FLANN匹配器 参数
FLANN_INDEX_KDTREE=0
indexParams=dict(algorithm =FLANN_INDEX_KDTREE,trees=5)
searchParams=dict(checks=50)    #

flann=cv2.FlannBasedMatcher(indexParams,searchParams)   #创建FLANN匹配器
#进行匹配操作
matches=flann.knnMatch(des1,des2,k=2)

#准备一个掩膜，用于得到好的匹配
matchesMask = [[0,0] for i in range(len(matches))]

#David G.Lowe的比率测试，生成掩膜
for i,(m,n) in enumerate(matches):
    if m.distance <0.7*n.distance:
        matchesMask[i]=[1,0]

drawParams = dict(matchColor = (0,255,0),
                  singlePointColor = (0,255,0),
                  matchesMask = matchesMask,
                  flags=0)
resultImage=cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,**drawParams)

plt.imshow(resultImage),plt.show()

while(True):
    if cv2.waitKey() & 0xff ==ord("q"):
        break
cv2.destroyAllWindows()